package br.com.fa7.controller;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import br.com.fa7.service.ManagementFight;

@WebServlet(urlPatterns = "/event", asyncSupported = true)
public class EventController extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private ManagementFight managementFight = new ManagementFight();
	private int requestNotUsed = 0;
	
	@Override
	public void init() throws ServletException {
		Thread treadFight = new Thread(managementFight);
		treadFight.start();
		
		super.init();
	}
	
	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {

		if(Boolean.toString(true).equalsIgnoreCase(request.getParameter("reset"))){
			managementFight.createNewFight();
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		}else{
			AsyncContext asyncContext = request.startAsync();
			if(managementFight.hasNewEvent()){
				asyncContext.getResponse().getWriter().write(managementFight.getCurrentFightStatus());
			}else{
				requestNotUsed++;
				System.out.println("Request Not Used " + requestNotUsed);
			}
			asyncContext.complete();
		}
		
	}

}
